package com.zyht.bank.wechat.utils;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;

/**
 * 图片处理公共类
 * 
 */
public class ImageUtil {

	/**
	 * 判断文件是否是图片，如果是，返回true，否则，返回false
	 * 
	 * @param fileByte
	 *            需要验证的File文件
	 * @return true or false
	 */
	public static boolean isImage(byte[] fileByte) {
		if (fileByte == null || fileByte.length <= 0) {
			return false;
		}
		try {
			ByteArrayInputStream in = new ByteArrayInputStream(fileByte);
			BufferedImage image = ImageIO.read(in);
			if (image != null) { // 如果image不为空，则说明file文件是图片
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 等比压缩图像
	 * 
	 * @param src
	 *            源图像文件
	 * @param target
	 *            压缩后要存放的目标文件
	 * @param maxWidth
	 *            压缩后允许的最大宽度
	 * @param maxHeight
	 *            压缩后允许的最大高度
	 * @throws java.io.IOException
	 */
	public static void transform(File srcFile, String target, int maxWidth, int maxHeight, String imageType) {
		try {
			String dirStr = target.substring(0, target.lastIndexOf("/") + 1);
			File dir = new File(dirStr);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File targetFile = new File(target);
			AffineTransform transform = new AffineTransform();
			BufferedImage biSrc = ImageIO.read(srcFile);
			int width = biSrc.getWidth();
			int height = biSrc.getHeight();
			int newWidth = maxWidth;
			int newHeight = maxHeight;
			double scaleX = (double) newWidth / width;
			double scaleY = (double) newHeight / height;
			transform.setToScale(scaleX, scaleY);
			AffineTransformOp ato = new AffineTransformOp(transform, null);
			BufferedImage biTarget = new BufferedImage(newWidth, newHeight, biSrc.getType());
			biTarget.getGraphics().drawImage(biSrc.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT), 0, 0,
					null);
			ato.filter(biSrc, biTarget);
			ImageIO.write(biTarget, imageType, targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 二值化图片(将图片灰度化,二值化等)
	 * 
	 * @param src
	 *            原图片路径
	 * @param target
	 *            新图片路径
	 * @param imageType
	 *            图片类型
	 * @param typeByte
	 *            二值化类型(参照BufferedImage的常量,如灰度化:BufferedImage.TYPE_BYTE_GRAY)
	 */
	public static void binaryImage(String src, String target, String imageType, int byteType) {
		try {
			File file = new File(src);
			BufferedImage image = ImageIO.read(file);
			int width = image.getWidth();
			int height = image.getHeight();
			// 灰度化 byteType=BufferedImage.TYPE_BYTE_GRAY
			BufferedImage binaryImage = new BufferedImage(width, height, byteType);
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					int rgb = image.getRGB(i, j);
					binaryImage.setRGB(i, j, rgb);
				}
			}
			File newFile = new File(target);
			ImageIO.write(binaryImage, imageType, newFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 按指定高度 等比例缩放图片
	 * 
	 * @param imageFile
	 * @param newPath
	 * @param newWidth
	 *            新图的宽度
	 * @throws IOException
	 */
	public static void zoomImageScale(File imageFile, String newPath, int newWidth) throws IOException {
		if (!imageFile.canRead())
			return;
		BufferedImage bufferedImage = ImageIO.read(imageFile);
		if (null == bufferedImage)
			return;

		int originalWidth = bufferedImage.getWidth();
		int originalHeight = bufferedImage.getHeight();

		double scale = (double) originalWidth / (double) newWidth; // 缩放的比例

		int newHeight = (int) (originalHeight / scale);
		zoomImage(imageFile, newPath, bufferedImage, newWidth, newHeight);
	}

	/**
	 * 等比例缩放图片
	 * 
	 * @param imageFile
	 * @param newPath
	 * @param newWidth
	 *            新图的宽度
	 * @throws IOException
	 */
	public static void zoomImageScale(String filePath, String newPath, int newWidth) throws IOException {
		File imageFile = new File(filePath);
		if (!imageFile.canRead())
			return;
		BufferedImage bufferedImage = ImageIO.read(imageFile);
		if (null == bufferedImage)
			return;

		int originalWidth = bufferedImage.getWidth();
		int originalHeight = bufferedImage.getHeight();

		double scale = (double) originalWidth / (double) newWidth; // 缩放的比例

		int newHeight = (int) (originalHeight / scale);

		zoomImage(imageFile, newPath, bufferedImage, newWidth, newHeight);
	}

	/**
	 * 旋转图片为指定角度
	 * 
	 * @author 王昌鸿
	 * @param bufferedimage
	 *            目标图像
	 * @param degree
	 *            旋转角度
	 * @return
	 */
	public static BufferedImage rotateImage(final BufferedImage bufferedimage, final int degree) {
		int w = bufferedimage.getWidth();
		int h = bufferedimage.getHeight();
		int type = bufferedimage.getColorModel().getTransparency();
		BufferedImage img;
		Graphics2D graphics2d;
		(graphics2d = (img = new BufferedImage(w, h, type)).createGraphics())
				.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);
		graphics2d.drawImage(bufferedimage, 0, 0, null);
		graphics2d.dispose();
		return img;
	}

	private static void zoomImage(File imageFile, String newPath, BufferedImage bufferedImage, int width, int height)
			throws IOException {

		String suffix = StringUtils.substringAfterLast(imageFile.getName(), ".");

		// 处理 png 背景变黑的问题
		if (suffix != null
				&& (suffix.trim().toLowerCase().endsWith("png") || suffix.trim().toLowerCase().endsWith("gif"))) {
			BufferedImage to = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = to.createGraphics();
			to = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
			g2d.dispose();

			g2d = to.createGraphics();
			Image from = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
			g2d.drawImage(from, 0, 0, null);
			g2d.drawRect(0, 0, width, height);
			// System.out.println("11111111111");
			ImageIO.write(to, suffix, new File(newPath));
		} else {
			// 图片的按照指定高度，宽度 进行普通的重绘
			BufferedImage newImage = new BufferedImage(width, height, bufferedImage.getType());
			Graphics g = newImage.getGraphics();
			g.drawImage(bufferedImage, 0, 0, width, height, null);
			g.dispose();
			// System.out.println("2222222222");
			ImageIO.write(newImage, suffix, new File(newPath));
		}
	}

	/**
	 * 对/upload/image/201611040154055590.jpg 路径根据传入参数进行更改
	 * 
	 * @param path
	 * @param context
	 * @return String
	 */
	public static String pathReplaceStr(String path, String context) {
		int type = path.lastIndexOf("/") + 1;
		String pathSub = path.substring(type, path.lastIndexOf("."));
		return path.replace(pathSub, pathSub + context);
	}

	public static String pathReplacePng(String path, String context) {
		int type = path.lastIndexOf("/") + 1;
		return path.substring(0, type) + path.substring(type, path.lastIndexOf(".")) + context;
	}

	public static void main(String[] args) throws IOException {

		File file = new File("F:/image");

		File[] files = file.listFiles();

		for (File f : files) {
			if (!f.isDirectory()) {
				String fileName = f.getName();
				String fileType = fileName.substring(fileName.lastIndexOf("."));
				System.out.println(fileType);

				zoomImageScale(f, "F:/image/img/" + System.currentTimeMillis() + "_small" + fileType, 500);
			}

		}
	}

}
